package com.maskota;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class Tiendas extends MapActivity {
	boolean internet;
	InputStream is = null;
	String result;
    MapView map=null;
	 MyLocationOverlay me=null;
	 String[] arraydireccion,arraytelefono,arrayx,arrayy;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tiendas);

		internet = isInternetConnectionActive(Tiendas.this);
		if (internet == true){
		Toast.makeText(getApplicationContext(), "SI INTERNET", Toast.LENGTH_SHORT).show();
		 enviarInfo();
		 map=(MapView)findViewById(R.id.map);			
		 map.getController().setCenter(getPoint(19.434820,-99.134003));
		map.getController().setZoom(17);
		map.setBuiltInZoomControls(true);
		
		Drawable marker=getResources().getDrawable(R.drawable.mapaicon);
		
		
		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
		 marker.getIntrinsicHeight());
		
		map.getOverlays().add(new SitesOverlay(marker));
		
		me=new MyLocationOverlay(this, map);
		map.getOverlays().add(me);
			
			
		}else if(internet == false){

            AlertDialog alertdialog=new AlertDialog.Builder(Tiendas.this).create();
			alertdialog.setIcon(R.drawable.ic_launcher);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	 alertdialog.setButton("OK", new DialogInterface.OnClickListener() {
	    	      public void onClick(DialogInterface dialog, int which) {
	    	 
	    	       finish();
	    	 
	    	    } });
	    	alertdialog.show();
		}
	}
	
	public static boolean isInternetConnectionActive(Context context) {
		  NetworkInfo networkInfo = ((ConnectivityManager) context
		    .getSystemService(Context.CONNECTIVITY_SERVICE))
		    .getActiveNetworkInfo();

		  if(networkInfo == null || !networkInfo.isConnected()) {
		   return false;
		  }
		  return true;
	}
	
	 protected void enviarInfo() {
         String url="http://maskota.zedtrix.com/?sec=api&accion=getTiendas";
         Log.i("url mia", ""+url);
                 
                 URI myURI = null;
                 try {
                         myURI = new URI(url);
                 } catch (URISyntaxException e) {
                 }
                 HttpClient httpClient = new DefaultHttpClient();
                 HttpGet getMethod = new HttpGet(myURI);
                 HttpResponse webServerResponse = null;
                 try {
                         webServerResponse = httpClient.execute(getMethod);
                 }  catch (IOException e) {
                 }
                 
                 HttpEntity httpEntity = webServerResponse.getEntity();
        
                 //MANEJO DE LA RESPUESTA DEL SERVIDOR
                 if (httpEntity != null) {
                         try {
                                 is = httpEntity.getContent();
                                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                     StringBuilder sb = new StringBuilder();
                     String line = null;
                     while ((line = reader.readLine()) != null) {
                             sb.append(line + "\n");
                     }
                     is.close();
                     result=sb.toString();
                     String array[]=result.trim().split("@@@");
                     arraydireccion = new String[array.length];
                     arraytelefono = new String[array.length];
                     arrayx = new String[array.length];
                     arrayy = new String[array.length];
                     
                     for(int i =0;i<array.length;i++){
                     Log.i("arrraycompleto", array[i])	;
                      }
                     
                     for(int i =0;i<array.length;i++){
                    	String array2[] = array[i].split("%%%");
                    	arraydireccion[i]=array2[0];
                     }
                     
                     for(int i =1;i<array.length;i++){
                    	String array2[] = array[i].trim().split("%%%");
                    	Log.i("Size",""+array2.length);
                    	arraytelefono[i]=array2[1];
                     }
                     
                     for(int i =1;i<array.length;i++){
                    	String array2[] = array[i].split("%%%");
                    	arrayx[i]=array2[2];
                     }
                     
                     for(int i =1;i<array.length;i++){
                    	String array2[] = array[i].split("%%%");
                    	arrayy[i]=array2[3];
                     }
                     
                     for(int i=0; i<array.length; i++){
                         Log.i("MI ARRAYDDIRECCIONES", ""+arraydireccion[i]);
                     }
                     for(int i=1; i<array.length; i++){
                       Log.i("MI ARRAYDTELEFONOS", ""+arraytelefono[i]);
                   }
                     for(int i=1; i<array.length; i++){
                         Log.i("MI ARRAYDXS", ""+arrayx[i]);
                     }
                     for(int i=1; i<array.length; i++){
                       Log.i("MI ARRAYDYS", ""+arrayy[i]);
                   }
                         } catch (IllegalStateException e) {
                                 e.printStackTrace();
                         } catch (IOException e) {
                         }
                 }
         }
	 
//	  @Override
//	  public void onResume() {
//		    super.onResume();
//		  internet = isInternetConnectionActive(Tiendas.this);
//			if (internet == true){
//
//	    me.enableMyLocation();
//	    me.enableCompass();
//			}else if(internet == false){
//
//	            AlertDialog alertdialog=new AlertDialog.Builder(Tiendas.this).create();
//				alertdialog.setIcon(R.drawable.ic_launcher);
//		    	alertdialog.setTitle("Aviso");
//		    	alertdialog.setMessage("Error de conectividad");
//		    	alertdialog.show();
//		    	finish();
//			}
//	  }   
	  
//	  @Override
//	  public void onPause() {
//	    super.onPause();
//	    
//	    me.disableCompass();
//	  }  
	  protected boolean isRouteDisplayed() {
	    return(false);
	  }
	  
	  @Override
	  public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_S) {
	      map.setSatellite(!map.isSatellite());
	      return(true);
	    }
	    else if (keyCode == KeyEvent.KEYCODE_Z) {
	      map.displayZoomControls(true);
	      return(true);
	    }
	    
	    return(super.onKeyDown(keyCode, event));
	  }

	  private GeoPoint getPoint(double lat, double lon) {
	    return(new GeoPoint((int)(lat*1000000.0),
	                          (int)(lon*1000000.0)));
	  }
	 
	  private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		    private List<OverlayItem> items=new ArrayList<OverlayItem>();
		    
		    public SitesOverlay(Drawable marker) {
		      super(marker);
		      
		      boundCenterBottom(marker);
		      for(int i =1; i<arraydireccion.length;i++){
		    	  items.add(new OverlayItem(getPoint(Double.parseDouble(arrayx[i].trim()),Double.parseDouble(arrayy[i].trim())), arraydireccion[i].trim(), arraytelefono[i].trim()));
		      }
		      populate();
		    }
		    
		    @Override
		    protected OverlayItem createItem(int i) {
		      return(items.get(i));
		    }
		    
		    @Override
		    protected boolean onTap(int i) {
		    	Dialog dialogo = new Dialog(Tiendas.this);
		    	dialogo.requestWindowFeature(Window.FEATURE_NO_TITLE);

		    	dialogo.setContentView(R.layout.customdialog);
		    	TextView direccion, telefono;
		    	
		    	direccion = (TextView) dialogo.findViewById(R.id.direccion);
		    	telefono = (TextView) dialogo.findViewById(R.id.telefono);
		    	direccion.setText(arraydireccion[i+1]);
		    	telefono.setText(arraytelefono[i+1]);
		    	
		    	dialogo.setCancelable(true);
		    	dialogo.show();
//		      Toast.makeText(Tiendas.this,
//		                      items.get(i+1).getSnippet()+"tel"+arraytelefono[i+1]+"direc"+arraydireccion[i+1],
//		                      Toast.LENGTH_SHORT).show();
		      return(true);
		    }
		    
		    @Override
		    public int size() {
		      return(items.size());
		    }
		  }
	 

}
